import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { login } from '@/api/login'
import { warning, delay } from '@web-utils/core'
import { get2FAToken, set2FAToken } from '@/util/auth'

export async function tfa(to, from, next) {
  if (get2FAToken() || process.env.NODE_ENV === 'development') {
    next()
    return
  }
  try {
    await MessageBox.prompt('请输入密码', {
      title: '安全验证',
      type: 'warning',
      inputType: 'password',
      closeOnClickModal: false,
      closeOnPressEscape: true,
      closeOnHashChange: true,
      inputErrorMessage: '密码长度不能小于 6 个字符',
      inputValidator(val) {
        return val?.length >= 6
      },
      inputPlaceholder: '请输入...',
      async beforeClose(action, instance, done) {
        if (action === 'confirm') {
          try {
            instance.confirmButtonLoading = true
            instance.showCancelButton = false
            instance.showClose = false
            instance.confirmButtonText = '验证中...'
            const res = await login({
              username: store.state.user.userName,
              password: instance.inputValue,
              grantType: undefined,
              deviceId: undefined,
              validCode: undefined
            })
            if (res && res.code === 0) {
              const token = res.data.access_token
              set2FAToken(token)
              done()
            } else {
              Message.warning('未知错误')
            }
          } catch (e) {
            instance.confirmButtonLoading = false
            instance.showCancelButton = true
            instance.showClose = true
            instance.confirmButtonText = '确定'
            warning.call(to.matched[to.matched.length - 1], e)
          }
        } else {
          done()
        }
      }
    })
    await delay(200)
    next()
  } catch (e) {
    next(false)
    warning.call(to.matched[to.matched.length - 1], e)
  }
}

export default {
  async beforeRouteEnter(to, from, next) {
    await tfa(to, from, next)
  }
}
